package com.shiku.imserver.repository;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.shiku.imserver.service.IMBeanUtils;
import org.bson.Document;

public class NewFirendRepository extends BaseRepository {
    private static final String NEWFIREND = "shiku_newFirend";
    private MongoDatabase newFriendDB;

    public boolean initialize() {
        try {
            this.newFriendDB = IMBeanUtils.getBeanManager().getMongoClient().getDatabase(NEWFIREND);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public void saveNewFirendRecord(String userId, String toUserId, Object from, short type, String content) {
        Document query = new Document("userId", userId);
        query.put("toUserId", toUserId);
        MongoCollection<Document> collection = getCollection(this.newFriendDB, Long.valueOf(userId).longValue());
        Document obj = (Document) collection.find(query).first();
        Document dbObj = new Document();
        long modifyTime = System.currentTimeMillis() / 1000;
        if (content == null) {
            content = "";
        }
        dbObj.put("direction", 0);
        dbObj.put("type", Short.valueOf(type));
        dbObj.put("content", content);
        dbObj.put("modifyTime", Long.valueOf(modifyTime));
        if (500 == type) {
            dbObj.put("from", from);
        }
        if (obj == null) {
            dbObj.put("userId", userId);
            dbObj.put("toUserId", toUserId);
            dbObj.put("createTime", Long.valueOf(modifyTime));
            collection.insertOne(dbObj);
        } else {
            collection.updateOne(query, new Document("$set", dbObj));
        }
        MongoCollection<Document> collectionTo = getCollection(this.newFriendDB, Long.valueOf(toUserId).longValue());
        query.put("userId", toUserId);
        query.put("toUserId", userId);
        Document obj2 = (Document) collectionTo.find(query).first();
        dbObj.remove("_id");
        dbObj.put("userId", toUserId);
        dbObj.put("toUserId", userId);
        dbObj.put("direction", 1);
        if (obj2 == null) {
            collectionTo.insertOne(dbObj);
        } else {
            collectionTo.updateOne(query, new Document("$set", dbObj));
        }
    }
}
